package net.j4love.netty.inaction.c2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author he peng
 * @create 2018/6/12 11:30
 * @see
 */

// 因为 @Sharable 对所有的客户端连接来说都会使用同一个 EchoServerHandler 实例
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("[" + Thread.currentThread().getName() + "] Thread ," +
                " Server Received : " + in.toString(CharsetUtil.UTF_8));
        in.writeBytes(DEFAULT_DATE_FORMAT.format(new Date()).toString().getBytes());
        ctx.write(in);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + Thread.currentThread().getName() + "] Thread , Read Completed Flush Buffer");
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
           .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("[" + Thread.currentThread().getName() + "] Thread , " +
                "Exception Caught , Remote Address [" + ctx.channel().remoteAddress() + "]");
        try {
            cause.printStackTrace();
        } finally {
            ctx.close();
        }
    }
}
